#!/usr/bin/python

import sys
import re

anno_file = sys.argv[1]

clusters_file = sys.argv[2]

af = open(anno_file, "rU")

cf = open(clusters_file, "rU")

al = af.readlines()

cl = cf.readlines()

clusters = {}

for line in cl:
    ltp = line
    l = ltp.split('\t')
    clusters[l[0]] = l[1].rstrip()

anno_count = len(al)

m1 = re.compile('(.*\[.*\].*)\[(.*)\]')
m2 = re.compile('(.*)\[(.*)\]')
m3 = re.compile('(hypothetical protein).*')
m4 = re.compile('(conserved hypothetical).*')

i = 0

while i < anno_count:
    gistoparse = al[i]
    ll = gistoparse.split('\t')
    pid = ll[0]
    locustag = ll[1]
    feat = ll[2]
    blast_status = ll[6]
    gi = ll[11]
    blastdef = ll[17]
    blastorg = ll[18]

    if feat == "tRNA":
        print locustag + "\t" + blastdef
    elif feat == "rRNA":
        print locustag + "\t" + blastdef
    elif feat == "CDS" and blast_status == "No": 
        print pid + "\t" + "hypothetical protein"
    elif feat == "CDS" and blast_status == "Yes":
        if gi != "Empty":
            if clusters.has_key(gi):
                d = clusters[gi]
                if m1.match(d):
                    pattern = m1.match(d)
                    print pid + "\t" + pattern.group(1) + "\t" + pattern.group(2)
                else:
                    pattern = m2.match(d)
                    print pid + "\t" + pattern.group(1) + "\t" + pattern.group(2)
            else:
                if m3.match(blastdef):
                    pattern = m3.match(blastdef)
                    print pid + "\t" + pattern.group(1) + "\t" + blastorg
                elif m4.match(blastdef):
                    pattern = m4.match(blastdef)
                    print pid + "\t" + pattern.group(1) + " protein" + "\t" + blastorg
                else:
                    print pid + "\t" + blastdef + "\t" + blastorg

        else:
            print pid + "\t" + blastdef + "\t" + blastorg

    i += 1
